<script setup>
import { ref, onMounted, watch } from 'vue'
import { useRoute } from 'vue-router'
import { getProductsByCategoryIdAndChildren } from '@/apis/category.js'

// 商品列表
const products = ref([])
// 加载状态
const loading = ref(false)
// 路由信息
const route = useRoute()

// 获取分类下的商品
const fetchProductsByCategory = async (categoryId) => {
  loading.value = true
  try {
    const res = await getProductsByCategoryIdAndChildren(categoryId)
    products.value = res.data || []
  } catch (error) {
    console.error('获取商品失败:', error)
    products.value = []
  } finally {
    loading.value = false
  }
}

// 监听路由变化
onMounted(() => {
  const categoryId = route.params.id
  if (categoryId) {
    fetchProductsByCategory(categoryId)
  }
})

// 监听路由参数变化
watch(
  () => route.params.id,
  (newId) => {
    if (newId) {
      fetchProductsByCategory(newId)
    }
  }
)
</script>

<template>
  <div class="category-container">
    <div class="container">
      <div class="goods-list" v-if="!loading">
        <div v-for="item in products" :key="item.pid" class="goods-item">
          <RouterLink :to="`/detail/${item.pid}`">
            <img :src="item.pimage1" :alt="item.pname" />
            <p class="name">{{ item.pname }}</p>
            <p class="desc">{{ item.pdetail }}</p>
          </RouterLink>
        </div>
      </div>
      <div v-else class="loading">加载中...</div>
    </div>
  </div>
</template>

<style scoped lang="scss">
.category-container {
  .container {
    padding: 20px;
  }
  
  .goods-list {
    display: flex;
    flex-wrap: wrap;
    gap: 20px;
    
    .goods-item {
      width: 300px;
      background: #f0f9f4;
      padding: 10px;
      border-radius: 8px;
      transition: all 0.5s;
      
      &:hover {
        transform: translate3d(0, -3px, 0);
        box-shadow: 0 3px 8px rgba(0, 0, 0, 0.2);
      }
      
      img {
        width: 100%;
        height: 300px;
        object-fit: cover;
      }
      
      p {
        font-size: 18px;
        padding-top: 8px;
        text-align: center;
        text-overflow: ellipsis;
        overflow: hidden;
        white-space: nowrap;
      }
      
      .desc {
        color: #999;
        font-size: 14px;
      }
    }
  }
  
  .loading {
    text-align: center;
    padding: 50px;
    font-size: 18px;
  }
}
</style>